package com.mark.springsecurity.config;

import org.springframework.data.domain.AuditorAware;
import org.springframework.lang.NonNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class AuditorAwareImpl implements AuditorAware<String> {

  @Override
  @NonNull
  public Optional<String> getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (isNotAuthenticated(authentication)) return Optional.of("robot");
    else return getUsernameFromAuthentication(authentication);
  }

  public boolean isNotAuthenticated(Authentication authentication) {
    return !authentication.isAuthenticated();
  }

  public Optional<String> getUsernameFromAuthentication(Authentication authentication) {
    Object principal = authentication.getPrincipal();
    if (instanceOfJwt(principal))
      return Optional.of(
          ((org.springframework.security.oauth2.jwt.Jwt) principal)
              .getClaims()
              .get("user_name")
              .toString());
    return Optional.of(principal.toString());
  }

  public boolean instanceOfJwt(Object principal) {
    return principal instanceof org.springframework.security.oauth2.jwt.Jwt;
  }
}
